$.ajaxSetup({
    cache: false
});
(function ($) {
    //UI调整
    Do.ready('check', function () {
        $('input').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass: 'iradio_minimal-blue'
        });
    });
    //表格处理
    $.fn.duxTable = function (options) {
        var defaults = {
            selectAll: '#selectAll',
            selectSubmit: '#selectSubmit',
            selectAction: '#selectAction',
            deleteUrl: '',
            actionUrl: '',
            actionParameter: {}
        }
        var options = $.extend(defaults, options);
        this.each(function () {
            var table = this;
            var id = $(this).attr('id');
            //处理多选单选
            $(options.selectAll).click(function () {
                $(table).find("[name='id[]']").each(function () {
                    if ($(this).prop("checked")) {
						$(this).iCheck('uncheck');
						$(this).prop("checked",false);
                    } else {
						$(this).iCheck('check');
						$(this).prop("checked",true);
                    }
                })
            });
            //处理批量提交
            $(options.selectSubmit).click(function () {
                Do.ready('tips', 'dialog', function () {
                    //记录获取
                    var ids = new Array();
                    $(table).find("[name='id[]']").each(function () {
                        if ($(this).prop("checked")) {
                            ids.push($(this).val());
                        }
                    })
                    toastr.options = {
                        "positionClass": "toast-bottom-right"
                    }
                    if (ids.length == 0) {
                        toastr.warning('请先选择操作记录');
                        return false;
                    }
                    //操作项目
                    $.dialog.confirm('你确认要进行本次批量操作！', function () {
                        var parameter = $.extend({
                                ids: ids,
                                type: $(options.selectAction).val()
                            },
                            options.actionParameter());
                        $.post(options.actionUrl, parameter, function (json) {
                            toastr.options = {
                                "positionClass": "toast-bottom-right"
                            }
                            if (json.status) {
                                toastr.success(json.info);
                                setTimeout(function () {
                                    window.location.reload();
                                }, 2000);
                            } else {
                                toastr.warning(json.info);
                            }
                        }, 'json');
                    });

                });
            });

            //处理删除
            $(table).find('.del').click(function () {
                var obj = this;
                var div = $(obj).parent().parent();
                var url = '';
                if (options.deleteUrl == '') {
                    url = $(obj).attr('url');
                } else {
                    url = options.deleteUrl;
                }
                Do.ready('tips', 'dialog', function () {
                    $.dialog.confirm('你确认删除操作？', function () {
                        $.post(url, {
                                data: $(obj).attr('data')
                            },
                            function (json) {
                                if (json.status) {
                                    toastr.success(json.info);
                                    div.remove();
                                } else {
                                    toastr.warning(json.info);
                                }
                            }, 'json');
                    });

                });
            });
            /*

            //处理ajax编辑
            $(table).find('.edit').click(function () {
                var oldText = $(this).text();
                var width = $(this).attr('width');
                var obj = this;
                var input = $(obj).find('input');
                var url = $(obj).attr('url');
                var name = $(obj).attr('name');
                if (input.length == 0) {
                    var html = '<input class="u-ipt" style="width:' + width + 'px;" value="' + oldText + '" type="text" />';
                    $(obj).html(html);
                    input = $(obj).find('input');
                }
                input.focus();
                input.blur(function () {
                    text = input.val();
                    $.post(url, {
                        name: name,
                        data: text
                    }, function (json) {
                        if (json.status == 'y') {
                            $(obj).text(json.info);
                        } else {
                            input.addClass('u-tta-err');
                            $.dialog.tips(json.info);
                        }
                    }, 'json');
                });
            });
			*/
        });
    };
    //表单处理
    $.fn.duxForm = function (options) {
        var defaults = {
            postFun: {},
            returnFun: {}
        }
        var options = $.extend(defaults, options);
        this.each(function () {
            //表单提交
            var form = this;
            Do.ready('form', function () {
                $(form).Validform({
                    ajaxPost: true,
                    postonce: true,
                    tiptype: function (msg, o, cssctl) {
                        if (!o.obj.is("form")) {
                            //设置提示信息
                            var objtip = o.obj.siblings(".help-block");
                            if (o.type == 2) {
                                //通过
                                var className = 'formitm-success';
                                $('#tips').html('');
                            }
                            if (o.type == 3) {
                                //未通过
                                var html = '<div class="u-alert u-alert-danger">您填写的信息未通过验证，请检查后重新提交！</div>';
                                $('#tips').html(html);
                                var className = 'formitm-danger';
                            }
                            //设置样式
                            o.obj.parents('.formitm').removeClass('formitm-success formitm-danger');
                            o.obj.parents('.formitm').addClass(className);
                            objtip.text(msg);
                        }
                    },
                    beforeSubmit: function (curform) {
                        //锁定按钮
                        $(form).find('#btn-group').find('button').attr('disabled', true);
                        $(form).find('#btn-submit').text($('#btn-submit').text() + '中...');
                        if ($.isFunction(options.postFun)) {
                            options.postFun();
                        }
                    },
                    callback: function (data) {
                        $(form).find('#btn-submit').text($('#btn-submit').text().replace('中...', ''));
                        if (data.status == 1) {
                            //成功返回
                            if ($.isFunction(options.returnFun)) {
                                options.returnFun(data);
                            } else {
                                if (data.url == null || data.url == '') {
                                    var html = '<div class="u-alert u-alert-success">' + data.info + '3秒后为您重新载入！</div>';
                                    $('#tips').html(html);
                                    window.setTimeout(function () {
                                        window.location.reload();
                                    }, 3000);
                                } else {
                                    var html = '<div class="u-alert u-alert-success">您可以 <a href="javascript:window.location.reload(); ">重新载入</a> 或 <a href="' + data.url + '">跳转</a>，无操作5秒后会系统会自动跳转。</div>';
                                    $('#tips').html(html);
                                    window.setTimeout(function () {
                                        window.location.href = options.returnUrl;
                                    }, 5000);
                                }
                            }
                        } else {
                            //失败返回
                            $(form).find('#btn-group').find('button').attr('disabled', false);
                            var html = '<div class="u-alert u-alert-danger">' + data.info + '</div>';
                            $('#tips').html(html);
                        }
                    }
                });
                //下拉赋值
                var assignObj = $(form).find('.dux-assign');
                assignObj.each(function () {
                    var assignTarget = $(this).attr('target');
                    $(this).change(function () {
                        $(assignTarget).val($(this).val());
                    });
                });
            });
        });
    };

    //编辑器调用
    $.fn.duxEditor = function (options) {
        var defaults = {
            uploadUrl: rootUrl + 'index.php?m=DuxCms&c=AdminUpload&a=upload',
            uploadParams: {
                relation_key: $('#relation_key').val()
            },
            config: {}
        }
        var options = $.extend(defaults, options);
        this.each(function () {
            //编辑器
            var id = '#' + $(this).attr('id');
            Do.ready('editor', 'uploadQueue', 'tips', function () {
				var editorConfig = {
                    language: 'zh_CN',
                    selector: id,
                    browser_spellcheck: false,
                    menubar: true,
                    convert_urls: false,
                    plugins: [
                        'advlist autolink lists link image charmap print preview hr anchor pagebreak',
                        'searchreplace visualblocks visualchars code fullscreen',
                        'insertdatetime media nonbreaking save table contextmenu directionality',
                        'emoticons template paste upload saveimages'
                    ], 
                    toolbar1: ' | insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', // 工具条1
                    toolbar2: 'print preview media | forecolor backcolor emoticons | upload saveimages', // 工具条2
                    uploadUrl: options.uploadUrl,
                    sessId: sessId,
                    setup: function (ed) {
                        ed.on('blur', function (e) {
                            tinymce.triggerSave();
                        });
                    }
                };
				tinymce.init(editorConfig);
				if ($(id).parents('#expand').length > 0) {
					//扩展字段重新绑定
					tinymce.remove(id);
					tinymce.init(editorConfig);
				}
            });
        });
    };

    //时间插件
    $.fn.duxTime = function (options) {
        var defaults = {
            lang: 'ch'
        }
        var options = $.extend(defaults, options);
        this.each(function () {
            var id = this;
            Do.ready('time', function () {
                $(id).datetimepicker(options);
            });
        });
    };

    //上传调用
    $.fn.duxFileUpload = function (options) {
        var defaults = {
            uploadUrl: rootUrl + 'index.php?m=DuxCms&c=AdminUpload&a=upload',
            type: [],
            uploadParams: {
            },
            complete: function () {}
        }
        var options = $.extend(defaults, options);
        this.each(function () {
            var upButton = $(this);
            var urlVal = upButton.attr('data');
            urlVal = $('#' + urlVal);
            var buttonText = upButton.text();
            var preview = upButton.attr('preview');
            preview = $('#' + preview);
			/* 图片预览 */
            preview.click(function () {
                if (urlVal.val() == '') {
                    toastr.warning('没有发现已上传图片！');
                } else {
                    window.open(urlVal.val());
                }
                return;
            });
			var Params = '';
            if(options.uploadParams){
                var urlArr = [];
                for(var key in options.uploadParams){
                    urlArr.push(key + '=' + options.uploadParams[key]);
                }
                Params = '&' + urlArr.join('&');
            }
			if(options.type){
				options.type = options.type.split(',');
			}
			/*创建上传*/
			Do.ready('juploader', function () {
                $.jUploader({
                    button: upButton.attr('id'), // 这里设置按钮id
                    action: options.uploadUrl + Params, // 这里设置上传处理接口，这个加了参数test_cancel=1来测试取消
                    allowedExtensions: options.type,
                    // 上传完成事件
                    onComplete: function (fileName, data) {
                        if (data.status){
                            urlVal.val(data.data.url);
                            options.complete(data.data);
                        }else{
                            alert(data.info);
                        }
                    }
                });
			});
        });
    };
	//多图上传
	$.fn.duxMultiUpload = function(options) {
		var defaults = {
			uploadUrl: rootUrl + 'index.php?m=DuxCms&c=AdminUpload&a=upload',
			uploadParams: {
				relation_key: $('#relation_key').val()
			},
			complete: function() {},
			uploadParamsCallback: function() {},
			type: ''
		}
		var options = $.extend(defaults, options);
		this.each(function() {
			var upButton = $(this);
			var dataName = upButton.attr('data');
			var div = $('#' + dataName);
			var data = div.attr('data');
			var buttonText = upButton.text();
			
			Do.ready('tips', 'upload', 'sortable', function () {
				/*创建上传*/
				var uploader = new plupload.Uploader({
					runtimes: 'html5,html4',
					browse_button: upButton.attr('id'),
					url: options.uploadUrl,
					filters: {
						mime_types: [{
							title: "上传文件",
							extensions: options.type
						}]
					}
				});
				uploader.init();
				//添加文件
				uploader.bind('FilesAdded', function (up, files){
					var ParamsCallback = options.uploadParamsCallback();
					uploader.settings.multipart_params = $.extend(options.uploadParams, ParamsCallback);
					uploader.start(true);
					buttonStatus(false);
					return true;
				});
				//上传进度
				uploader.bind('UploadProgress', function (up, file){
					upButton.text('上传：' + file.percent + '%');
				});
				//上传回调
				uploader.bind('FileUploaded', function (up, file, data){
					data = data.response;
					data = eval('(' + data + ')');
					if (data.status){
						htmlList(data.data.file);
						options.complete(data.data.file,file);
						return true;
					}else{
						uploader.splice();
						toastr.warning(data.info);
						buttonStatus(true);
						return false;
					}
				});
				//上传完毕
				uploader.bind('UploadComplete', function (up, files){
					upButton.text(buttonText);
					buttonStatus(true);
					div.sortable().on('sortupdate');
				});
				//错误提示
				uploader.bind('Error', function (up, err)
				{
					toastr.warning(err.message);
				}
				);
				/*按钮状态*/
				function buttonStatus(status) {
				   if (status) {
						uploader.disableBrowse(false);
						$(upButton).attr('disabled', false);
					} else {
						uploader.disableBrowse(true);
						$(upButton).attr('disabled', true);
					}
				}
				//处理上传列表
				function htmlList(file) {
					var html = '<li>\
					<a class="close" href="javascript:;">×</a>\
					<div class="img"><span class="pic"><img src="' + file.url + '" width="80" height="80" /></span></div>\
					<div class="title">\
					<input name="' + dataName + '[url][]" type="hidden" value="' + file.url + '" />\
					<input name="' + dataName + '[title][]" type="text" value="' + file.title + '" />\
					</div>\
					</li>';
					div.append(html);
				}
				//处理删除
				div.on('click', '.close',function() {
					$(this).parent().remove();
				});
			});
		});
	};
	
	//表单页面处理
        $.fn.duxFormPage = function (options) {
            var defaults = {
                uploadUrl: rootUrl + 'index.php?m=DuxCms&c=AdminUpload&a=upload',
                uploadComplete: function () {},
                uploadParams: function () {},
				uploadType : [],
                postFun: {},
                returnUrl: '',
                returnFun: {},
				form: true
            }
            var options = $.extend(defaults, options);
            this.each(function () {
                var form = this;
                form = $(form);
                //表单处理
				if(options.form){
					form.duxForm({
						postFun: options.postFun,
						returnUrl: options.returnUrl,
						returnFun: options.returnFun
					});
				}
                //文件上传
                if (form.find(".u-file-upload").length > 0) {
                    form.find('.u-file-upload').duxFileUpload({
						type: options.uploadType,
                        uploadUrl: options.uploadUrl,
                        complete: options.uploadComplete,
                        uploadParams: options.uploadParams
                    });
                }
				//图片上传
                if (form.find(".u-img-upload").length > 0) {
                    form.find('.u-img-upload').duxFileUpload({
						type: 'jpg,png,gif,bmp,jpeg',
                        uploadUrl: options.uploadUrl,
                        complete: options.uploadComplete,
                        uploadParams: options.uploadParams
                    });
                }
				//多图片上传
                if (form.find(".u-multi-upload").length > 0) {
                    form.find('.u-multi-upload').duxMultiUpload({
						type: 'jpg,png,gif,bmp,jpeg',
                        uploadUrl: options.uploadUrl,
                        complete: options.uploadComplete,
                        uploadParamsCallback: options.uploadParamsCallback
                    });
                }
                //编辑器
                if (form.find(".u-editor").length > 0) {
                    form.find('.u-editor').duxEditor({
                        uploadUrl: options.uploadUrl
                    });
                }
                //时间选择
                if (form.find(".u-time").length > 0) {
                    form.find('.u-time').duxTime();
                }
            });
        };
})(jQuery);